# import matplotlib.pyplot as plt
# import numpy as np
#
# def Line():
#     #从文本框获取，而不作为函数输入
#     #绘制一条线
#     if xpoint==None:
#         ypoints = np.array(ypoint)
#         plt.plot(ypoints)
#     elif ypoint==None:
#         xpoints = np.array(xpoint)
#         plt.plot(xpoints)
#     elif xpoint and ypoint :
#         [1, 8], [3, 10]  # (1,3)-(8,10)
#         xpoints = np.array(xpoint)
#         ypoints = np.array(ypoint)
#         plt.plot(xpoints, ypoints)
#     else:#xy点均孔
#         print('请至少输入一组坐标')
#     #绘制多条假设记录为n
#
#
#
#     #仅绘制坐标点
#     #plt.plot(xpoints, ypoints,'o')
#
#     plt.show()
#
#
#
# Line()

from PySide2.QtWidgets import QApplication, QMessageBox
from PySide2.QtUiTools import QUiLoader
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from PySide2.QtWidgets import QGraphicsScene
import matplotlib

matplotlib.use("Qt5Agg")


class MyFigureCanvas(FigureCanvas):
    """
    通过继承FigureCanvas类，使得该类既是一个PyQt5的Qwidget，又是一个matplotlib的FigureCanvas，这是连接pyqt5与matplotlib的关键
    """

    def __init__(self, parent=None, width=10, height=5, xlim=(0, 2500), ylim=(-2, 2), dpi=100):
        # 初始化时将图片的长、宽、像素均初始化给定
        # 其中xlim，ylim 表示横纵坐标的显示范围
        # 创建一个Figure
        self.figure = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
        FigureCanvas.__init__(self, self.figure)  # 初始化父类
        self.setParent(parent)

        self.fig1 = self.figure.add_subplot(111)  # 添加子图
        # add_subplot(2,2,4) 添加子图函数，三个参数分别表示纵向分几个子图，横向分几个子图，当前为第几个子图
        self.fig1.spines['top'].set_visible(False)  # 去掉绘图时上面的横线
        self.fig1.spines['right'].set_visible(False)  # 去掉绘图时右面的横线
        self.fig1.set_xlim(xlim)
        self.fig1.set_ylim(ylim)


class Stats(FigureCanvas):

    def __init__(self, parent=None, width=10, height=5, dpi=100):
        # 从文件中加载UI定义
        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        self.ui = QUiLoader().load('ui/window.ui')

        self.ui.pushButton.clicked.connect(self.plotdraw)

        self.gv_visual_data_content = MyFigureCanvas(width=self.ui.graphicsView.width() / 100,
                                                     height=self.ui.graphicsView.height() / 100,
                                                     xlim=(0, 2 * np.pi),
                                                     ylim=(-1, 1)
                                                     )

    def plotdraw(self):
        # 从文本框获取，而不作为函数输入
        #不同数字空格隔开
        xpoint = self.ui.plainTextEdit.toPlainText()
        ypoint = self.ui.plainTextEdit_2.toPlainText()
        print(xpoint,ypoint)
        xpoints=xpoint.split()
        ypoints=ypoint.split()
        # for i in xpoint:
        #     if i !=' ':
        #         xpoints.append(i)
        #
        # for I in ypoint:
        #     if I !=' ':
        #         ypoints.append(I)
        print(xpoints,ypoints)

        if xpoint or ypoint == ['']:
            if xpoint == ['']:
                self.gv_visual_data_content.fig1.plot(ypoints)#没自动跟随
                self.graphic_scene = QGraphicsScene()
                self.graphic_scene.addWidget(self.gv_visual_data_content)
                self.ui.graphicsView.setScene(self.graphic_scene)
                self.ui.graphicsView.show()

                # plt.plot(ypoints)
            else:
                self.gv_visual_data_content.fig1.plot(xpoints)
                self.graphic_scene = QGraphicsScene()
                self.graphic_scene.addWidget(self.gv_visual_data_content)
                self.ui.graphicsView.setScene(self.graphic_scene)
                self.ui.graphicsView.show()
                # plt.plot(xpoints)
        elif xpoint and ypoint !=['']:
            # [1, 8], [3, 10]  # (1,3)-(8,10)
            # plt.plot(xpoints, ypoints)
            self.gv_visual_data_content.fig1.plot(xpoints, ypoints)
            self.graphic_scene = QGraphicsScene()
            self.graphic_scene.addWidget(self.gv_visual_data_content)
            self.ui.graphicsView.setScene(self.graphic_scene)
            self.ui.graphicsView.show()

        else:  # xy点均孔
            print('请至少输入一组坐标')
            QMessageBox.warning(
                self.ui,
                '坐标错误',
                '请至少输入一个x或者y坐标')
        plt.show()

    def plot_cos(self):
        x = np.arange(0, 2 * np.pi, np.pi / 100)
        y = np.cos(x)
        self.gv_visual_data_content.fig1.plot(x, y)  # 在加在的图形gv_visual_data_content中的子图fig1中画图
        self.gv_visual_data_content.fig1.set_title('cos()')  # 设置图名
        self.graphic_scene = QGraphicsScene()  # 创建一个QGraphicsScene
        # 加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
        self.graphic_scene.addWidget(self.gv_visual_data_content)
        # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到放到QGraphicsScene中的
        self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
        self.ui.graphicsView.show()  # 调用show方法呈现图形

    # def plot_line(self):
    #     xpoints=xpoint
    #     ypoints=ypoint
    #     self.gv_visual_data_content.fig1.plot(xpoints,ypoints)


if __name__ == "__main__":
    app = QApplication([])
    # 实例化窗口

    mainwindow = Stats()
    mainwindow.ui.show()
    app.exec_()
